//
//  YZMainTabBarController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/21.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMainTabBarController.h"
#import "YZMControllerManager.h"
#import "YZMNavigationController.h"
#import "YZMAppStyle.h"
#import "YZClient+Trade.h"
#import "YZGeneralResultModel.h"
#import "YZMSaleTradePacket.h"
#import "YZClient+TDTrade.h"

@interface YZMControllerManager (__privated)

- (void)setupBtNibObject: (YZMainTabBarController *)ctrl;

@end

@interface YZMainTabBarController ()<UITabBarControllerDelegate>

@property (nonatomic, strong) UINavigationController *tradeFakeController;

@property (nonatomic, strong) NSMutableArray *dataList;

@property (nonatomic, strong) NSMutableArray *dataListforD;

@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation YZMainTabBarController



- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName: nibNameOrNil bundle: nibBundleOrNil];
    if (self) {
        [self initTabs];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [[YZMControllerManager sharedManager] setupBtNibObject: self];
    [self initTabs];
}


- (void)initTabs
{
    [YZMAppStyle customAppApearance];
    _dataList = [NSMutableArray array];
    _dataListforD = [NSMutableArray array];
//    self.tabBar.translucent = YES;
    self.delegate = self;
    
    NSArray *tabPageNames = @[@"home",@"custom",@"stock",@"discovery", @"mine"];
    NSArray *tabTitles = @[@"首页", @"自选", @"交易",@"发现",@"我的"];
    if (!YZMSWitchOn) {
        tabPageNames = @[@"homereview",@"baseterm",@"infoReview",@"answer",@"fbmine"];
        tabTitles = @[@"首页", @"基础术语", @"投资分析",@"答疑",@"我的"];
    }
    
    NSMutableArray *tabNavCtlrs = [NSMutableArray array];
    
    for (NSString *pageName in tabPageNames) {
        
        if ([pageName isEqualToString:@"stock"]) {
            
            UINavigationController *navCtrl = [[YZMNavigationController alloc] initWithRootViewController:[UIViewController new]];
            [tabNavCtlrs addObject:navCtrl];
            self.tradeFakeController = navCtrl;
            
        }else{
            UIViewController *pageCtrl = [YZMCMInstance viewControllerForName: pageName withParams: nil];
            if (pageCtrl) {
                UINavigationController *navCtrl = [[YZMNavigationController alloc] initWithRootViewController: pageCtrl];
                navCtrl.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"测试" image: nil selectedImage: nil];
                [tabNavCtlrs addObject: navCtrl];
            }
        }
    }
    
    self.viewControllers = tabNavCtlrs;
    
    for (NSInteger i = 0; i < tabNavCtlrs.count && i < tabTitles.count; i++) {
        UITabBarItem *tabItem = self.tabBar.items[i];
        tabItem.title = tabTitles[i];
    }
    for (NSInteger i = 0; i < tabPageNames.count; i++) {
        NSString *imageName = [@"icon_tabbar_" stringByAppendingString:tabPageNames[i]];
        NSString *highImageNamge = [imageName stringByAppendingString: @"_high"];
        UITabBarItem *tabItem = self.tabBar.items[i];
        UIOffset offset = UIOffsetMake(0, -5);
        tabItem.titlePositionAdjustment = offset;
        tabItem.image = [[UIImage imageNamed: imageName] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
        tabItem.selectedImage = [[UIImage imageNamed: highImageNamge] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal];
    }
    for (NSInteger j = 0; j < self.tabBar.subviews.count; j++) {
        id iv = self.tabBar.subviews[j];
        if ([tabPageNames[j] isEqualToString:@"stock"]) {
            UIButton *btn = (UIButton *)iv;
            for (UIImageView *imageView in btn.subviews) {
                if ([imageView isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
                    UIImageView *imageViewBorder = [[UIImageView alloc] init];
                    imageViewBorder.image = [UIImage imageNamed:@"Oval"];
                    imageViewBorder.userInteractionEnabled = YES;
                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectIndex)];
                    [imageViewBorder addGestureRecognizer:tap];
                    [btn insertSubview:imageViewBorder belowSubview:imageView];
                    [imageViewBorder mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.center.equalTo(imageView);
                        make.width.equalTo(@74);
                        make.height.equalTo(@68);
                    }];
                }
            }
            break;
        }
    }
}

- (void)selectIndex{
    [self pushNextVc];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if (viewController == self.tradeFakeController) {
        [self pushNextVc];
        return NO;
    }
    return YES;
}

- (void)pushNextVc{
    if (![YZMUserService sharedService].currentUser) {
        //未登录 跳转到 T+1 点买页面
        [YZMCMInstance pushViewControllerWithName: @"stock" andParams: nil];
        return;
    }
    self.hud = [MBProgressHUD showHUDAddedTo:[[YZMCMInstance.currentNavationCtroller visibleViewController] view] animated:YES];
    dispatch_group_t serviceGroup = dispatch_group_create();
    
    // Start the first service
    dispatch_group_enter(serviceGroup);
    
    [self fetchItemList:serviceGroup];
    
    // Start the second service
    dispatch_group_enter(serviceGroup);
    [self fetchItemListforD:serviceGroup];
    
    
    dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
        [self.hud setHidden:YES];
        //用户登录无持仓情况 跳转到 T+1 点买页面 切换跳转到T+D 点买页面
        if (self.dataList.count == 0 && self.dataListforD.count == 0) {
            [YZMCMInstance pushViewControllerWithName: @"stock" andParams:@{scrollIndexTOne:@0,scrollIndexTD:@0}];
            return;
        }
        //用户登录有持仓情况 T+1有持仓 T+D没有持仓 跳转到 T+1 点卖页面 切换跳转到T+D 点买页面
        if (self.dataList.count > 0 && self.dataListforD.count == 0) {
             [YZMCMInstance pushViewControllerWithName: @"stock" andParams: @{scrollIndexTOne:@1,scrollIndexTD:@0}];
            return;
        }
        // 用户登录有持仓情况 T+1与T+D 都有持仓 跳转到 T+1 点卖页面 切换跳转到T+D 点卖页面
        if (self.dataList.count > 0 && self.dataListforD.count > 0) {
            [YZMCMInstance pushViewControllerWithName: @"stock" andParams: @{scrollIndexTOne:@1,scrollIndexTD:@1}];
            return;
        }
        //用户登录有持仓情况 只有T+D有持仓 跳转到 T+D 点卖页面
        if (self.dataList.count == 0 && self.dataListforD.count > 0) {
            [YZMCMInstance pushViewControllerWithName: @"stockTD" andParams: @{scrollIndexTOne:@0,scrollIndexTD:@1}];
            return;
        }
    });
}

- (void)fetchItemList:(dispatch_group_t)serviceGroup{
    [self.dataList removeAllObjects];
    /*无网处理*/
    if (kNetworkNotReachability) {
        dispatch_group_leave(serviceGroup);
        return;
    }
    WS(ws);
    [YZClient td_fetchSaleTradeListWithPage:1 andPageSize:2 andTimeEnd:@"" success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            YZMSaleTradePacket *result = topModel.data;

            NSArray *sList = result.items;
            [ws.dataList removeAllObjects];
            [ws.dataList addObjectsFromArray:sList];
        }else{
            [ws.dataList removeAllObjects];
            [topModel showMessage];
        }
        dispatch_group_leave(serviceGroup);
    } failure:^(NSError *error) {
         [error yz_showMessage];
        dispatch_group_leave(serviceGroup);
    }];
}

- (void)fetchItemListforD:(dispatch_group_t)serviceGroup{
    /*无网处理*/
    [self.dataListforD removeAllObjects];
    if (kNetworkNotReachability) {
        dispatch_group_leave(serviceGroup);
        return;
    }
    WS(ws);
    [YZClient td_fetchSaleTradeListForDsuccess:^(NSURLResponse *response, id responseObject) {
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                NSArray *array =  topModel.data;
                [ws.dataListforD addObjectsFromArray:array];
            }
        dispatch_group_leave(serviceGroup);
        } failure:^(NSError *error) {
            [error yz_showMessage];
            dispatch_group_leave(serviceGroup);
        }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (UIViewController *)childViewControllerForStatusBarStyle
{
    return nil;
}

@end
